//1、引入http模块
const http = require('http');
const lark = require("@larksuiteoapi/node-sdk");
const {exec} = require('child_process');


const FEISHU_APP_ID = "cli_a5353776bba9100d";
const FEISHU_APP_SECRET = "nSNp3X7T6NWgP7kkY3Rt9dGJpfjBbPcR";

const client = new lark.Client({
    appId: FEISHU_APP_ID,
    appSecret: FEISHU_APP_SECRET,
    disableTokenCache: false,
    appType: lark.AppType.SelfBuild,
    domain: lark.Domain.Feishu,
});

const EVENT = new Set("");
const MESSAGE_ID_TO_CHAT_ID_MAP = new Map()

const pickRequestData = (req) => new Promise((resolve) => {
    let chunks = '';
    req.on('data', (chunk) => {
        chunks += chunk;
    });

    req.on('end', () => {
        const data = JSON.parse(chunks);
        resolve(data);
    });
});


const server = http.createServer(async (req, res) => {
    try {
        console.log('请求方式-----------：', req.method + " -- start");
        console.log(req.headers['host']);
        if (req.method === 'POST') {
            const data = (await pickRequestData(req));
            console.log(data);
            if (data.type === 'url_verification') { //检验
                res.end(JSON.stringify({
                    challenge: data.challenge,
                }));
            } else if (data.header?.event_type === 'im.message.receive_v1') { //处理接收消息
                let eventId = data.header.event_id;
                // 对于同一个事件，只处理一次
                console.log(EVENT);
                if (EVENT.has(eventId)) {
                    console.log("同一个事件，只处理一次");
                    return
                }
                EVENT.add(eventId)
                let updated_time = new Date(data.event.message.update_time)
                data.event.message.update_time
                let now = new Date()
                console.log("updated_time:" + updated_time);
                console.log("now:" + now);
                if (now - updated_time > 60) {
                    console.log("超过1分钟,不处理");
                    return
                }

                await receive_v1(data)
            } else {
                const {action: {tag}} = data
                if (tag === "select_static") {
                    await handle_build_event(data)
                    res.end(JSON.stringify({method: `${req.method}`, code: 1, msg: 'Success'}))
                } else {
                    res.end(JSON.stringify({method: `${req.method}`, code: 1, msg: 'Success'}))
                }
            }
        } else {
            res.end(JSON.stringify({method: `${req.method}`, code: 1, msg: 'Success'}))
        }
        console.log('请求方式-----------：', req.method + " -- end\n");
    } catch (e) {
        console.error(`处理消息错误: ${e}`);
    }
});


//{
//   app_id: 'cli_a5353776bba9100d',
//   open_id: 'ou_e7658f978e3d479c9535a878a01c94f0',
//   user_id: 'ggab3e1c',
//   open_message_id: 'om_6f89faa31752eb93ef590e38319b64ac',
//   tenant_key: '2cac2bb1a4cd175e',
//   token: 'c-f9a6a5e3c59b8e9eff5e0c5cee195423a561e0e2',
//   action: { tag: 'select_static', option: 'Debug' }
// }
//处理构建消息
async function handle_build_event(data) {
    const {open_id, open_message_id, action: {tag, option}} = data

    await build_job(open_id, open_message_id)
    if (option === 'Local') {

    } else if (option === "ReleaseDebug") {

    } else if (option === "Release") {

    } else {

    }
}


async function build_job(open_id, open_message_id) {
    const command = 'java -jar jenkins-cli.jar -s  http://localhost:8080/ -auth Fish:123456 build buildDebugAndUploadPgyer'
    exec(command, (error, stdout, stderr) => {
        if (error) {
            console.error(`build_job 执行错误: ${error}`)
            let data = MESSAGE_ID_TO_CHAT_ID_MAP.get(open_message_id)
            console.log(data)
            if (data?.chat_id) {
                //reply(data?.message_id, "打包失败...，请联系开发人员查看问题")
                only_show_buildFailed(data?.chat_id, open_id)
            }
            return;
        }
        only_hide_card(open_message_id)
        let data = MESSAGE_ID_TO_CHAT_ID_MAP.get(open_message_id)
        MESSAGE_ID_TO_CHAT_ID_MAP.delete(open_message_id)
        if (data?.message_id) {
            reply(data?.message_id, "正在打包...")
        }
        console.log(`输出结果:\n${stdout}`);
    });
}


async function reply(messageId, msg) {
    try {
        await client.im.message.reply({
            path: {
                message_id: messageId,
            }, data: {
                content: JSON.stringify({text: msg}), msg_type: 'text',
            },
        });
    } catch (error) {
        console.error("reply error start");
        console.error("messageId:" + messageId + " msg:" + msg);
        console.error(error.data);
        console.error("reply error end");
    }
}


//发送对特定人可见的卡片
async function only_show_card(chat_id, messageId, open_id) {
    try {
        const result = await client.request({
            method: "POST",
            url: '/open-apis/ephemeral/v1/send',
            data: {
                chat_id: chat_id,
                open_id: open_id,
                msg_type: "interactive",
                card: {
                    type: "template",
                    data: {
                        template_id: "ctp_AAiWZwt1wsse" //模版id
                    }
                }
            }
        });
        console.log("only_show_card success");
        console.log(result);
        MESSAGE_ID_TO_CHAT_ID_MAP.set(result.data.message_id, {chat_id: chat_id, messageId: messageId})
    } catch (error) {
        console.log("only_show_card error");
        console.error(error.data);
    }
}


//发送对特定人可见的卡片
async function only_show_buildFailed(chat_id, open_id) {
    try {
        const result = await client.request({
            method: "POST",
            url: '/open-apis/ephemeral/v1/send',
            data: {
                chat_id: chat_id,
                open_id: open_id,
                msg_type: "interactive",
                card: {
                    type: "template",
                    data: {
                        template_id: "ctp_AA1MpSPZqgjZ" //模版id
                    }
                }
            }
        });
        console.log("only_show_buildFailed success");
        console.log(result);
    } catch (error) {
        console.error("only_show_buildFailed error");
        console.error(error.data);
    }
}


//https://open.feishu.cn/document/server-docs/im-v1/message-card/delete-message-cards-that-are-only-visible-to-certain-people
//删除仅特定人可见的消息卡片
async function only_hide_card(message_id) {
    try {
        const result = await client.request({
            method: "POST", url: '/open-apis/ephemeral/v1/delete', data: {
                message_id: message_id
            }
        });
        console.log(result); // 输出 'Hello World'
    } catch (error) {
        console.error(error);
    }
}


async function receive_v1(data) {
    console.log("------im.message.receive_v1 start");
    console.log(data);
    const messageId = data.event.message.message_id;
    const message_type = data.event.message.message_type;
    if (message_type === "text") {
        const msg = JSON.parse(data.event.message.content).text;
        if (msg.endsWith("build")) {
            await only_show_card(data.event.message.chat_id, messageId, data.event.sender?.sender_id?.open_id)
        } else {
            const res = await reply(messageId, "暂不支持其他类型，仅支持 build")
            console.log("res")
            console.log(res)
        }
    } else {
        await reply(messageId, "暂不支持其他类型，仅支持 build")
    }
    console.log("------im.message.receive_v1 end");
    return {code: 1}
}


//4、监听端口号：指定服务器所使用的端口号
//可以通过内网穿透方式访问本地端口
server.listen(8899)
console.log('服务器已启动，监听8899端口，请访问 localhost:8899 ');